package main

import (
	"fmt"
	"google.golang.org/grpc"
	"io"
	"log"
	"net"
	"os"
	"server_stream_server/proto"
)

type FileService struct {
	proto.UnimplementedFileServiceServer
}

func (FileService) DownLoad(req *proto.FileRequest, stream proto.FileService_DownLoadServer) error {
	fmt.Println(req)
	file, err := os.Open("/mnt/grpc-go-1.60.0.zip")
	if err != nil {
		panic(err)
	}
	defer file.Close()
	var i = 1
	for {
		buf := make([]byte, 1024)
		_, err = file.Read(buf)
		if err == io.EOF {
			break
		}

		if err != nil {
			panic(err)
		}
		log.Printf("发送%d次\n", i)
		i++
		err := stream.Send(&proto.FileResponse{
			Content: buf,
		})
		if err != nil {
			log.Fatal(err)
			return err
		}
	}
	return nil
}

func main() {
	listen, _ := net.Listen("tcp", ":7070")
	// 创建grpc服务
	grpcServer := grpc.NewServer()
	// 注册服务
	proto.RegisterFileServiceServer(grpcServer, &FileService{})
	// 启动服务
	err := grpcServer.Serve(listen)
	if err != nil {
		log.Fatal("服务启动失败：", err)
		return
	}
}
